import { getLocalStorage, getCurrentTime, getCurrentNextMonth } from '@/utils/commonMethods';

// 数字千分位
export const AmountSlite = (value) => {
  const regExp = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g;
  const ret = (value + '').replace(regExp, '$1,');
  return ret;
};

// 去除数字千分位
export function rmAmountSlite(s) {
  return parseFloat(s.replace(/[^\d\.-]/g, ''));
}

// 附件上传限制
export const fileReject = ['html', 'bat', 'xml', 'exec', 'jsp', 'jspx'];

// 金额大写
export const digitUppercase = (n) => {
  const fraction = ['角', '分'];
  const digit = [
    '零', '壹', '贰', '叁', '肆',
    '伍', '陆', '柒', '捌', '玖'
  ];
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ];
  const head = n < 0 ? '负' : '';
  n = Math.abs(n);
  let s = '';
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(Math.floor(n * 1000 * 10 * Math.pow(10, i)) % (10 * 1000) / 1000)] + fraction[i]).replace(/零./, '');
  }
  s = s || '整';
  n = Math.floor(n);
  for (let i = 0; i < unit[0].length && n > 0; i++) {
    let p = '';
    for (let j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p;
      n = Math.floor(n / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  }
  return head + s.replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '零元整');
};

// 随机数
export function getRandomNum(Min, Max) {
  const Range = Max - Min;
  const Rand = Math.random();
  return Min + Math.round(Rand * Range);
}

// 遍历递归tree
export function digui(datas) {
  for (const key in datas) {
    const obj = {
      'title': datas[key].title,
      'icon': datas[key].icon || null
    };
    datas[key].meta = obj;
    if (datas[key].children) {
      digui(datas[key].children);
    }
  }
}

// 防抖
export function debounce(funct, delay) {
  let timer = null;
  return (...args) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      funct.apply(this, args);
    }, delay);
  };
}

// 深度克隆
export function cloneUtil(target) {
  // 判断目标数据是对象还是数组
  // [object Array]  [object Object]  [object Function]
  const type = Object.prototype.toString.call(target);
  let res;
  if (type.includes('Array')) {
    res = [];
  } else if (type.includes('Object')) {
    res = {};
  } else {
    return '';
  }
  for (const i in target) {
    if (typeof target[i] === 'object') {
      res[i] = cloneUtil(target[i]);
    } else {
      res[i] = target[i];
    }
  }

  return res;
}
// json转form-data
export function objectToFormData(obj, form, namespace) {
  const fd = form || new FormData();
  let formKey;

  for (const property in obj) {
    if (obj.hasOwnProperty(property)) {
      const key = Array.isArray(obj) ? '[]' : `[${property}]`;
      if (namespace) {
        formKey = namespace + key;
      } else {
        formKey = property;
      }
      // if the property is an object, but not a File, use recursivity.
      if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        objectToFormData(obj[property], fd, formKey);
      } else {
        // if it's a string or a File object
        fd.append(formKey, obj[property]);
      }
    }
  }

  return fd;
}
export function formatDate(date, fmt) {
  // 获取年份
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, String(date.getFullYear()).substr(4 - RegExp.$1.length));
  }
  // 获取m+ d+ h+ m+ s+
  /*
		M+   :正则表达式的一个规则  这里的'+'表示不确定M的个数（可能一个可能多个）
	* */
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = String(o[k]);
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
    }
  }
  return fmt;
}
function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

/**
 *
 *
 * @export
 * @param {* } key 系统变量key
 * @return {*} 找到该系统变量返回value 否则返回 ''
 */
export function getSystemVariable(key) {
  const date = getCurrentTime().split(' ')[0];
  const keyMap = {
    'sys_date': () => {
      return date;
    },
    'currentYear': () => {
      return date.split('-')[0];
    },
    'currentMonth': () => {
      return date.split('-')[0] + '-' + date.split('-')[1];
    },
    'currentNextMonth': () => {
      return getCurrentNextMonth();
    }
  };
  // 是否在本地内存中
  if (key in keyMap) {
    return keyMap[key]();
  } else {
    const value = getLocalStorage(key);
    if (value && (value[0] === '[' || value[0] === '{')) {
      return JSON.parse(value);
    } else {
      return value || '';
    }
  }
}

// export function getSystemVariable(key) {
// const keyMap = {
//   // 系统日期
//   'sys_date': () => {
//     const re = /(?<year>\d{4})\/(?<month>\d{1,2})\/(?<date>\d{1,2})/u;
//     return new Date().toLocaleDateString().replace(re, '$<year>-$<month>-$<date>');
//   },

//   // 当前用户名称
//   'xcNickName': () => {
//     return localStorage.getItem('xcNickName') || '';
//   },

//   'phone': () => {
//     return localStorage.getItem('phone') || '';
//   },

//   // 发起人部门
//   'enterpriseList': () => {
//     return localStorage.getItem('xcRoleName') || '';
//   },

//   'showAvatar': () => {
//     return localStorage.getItem('showAvatar') || '';
//   }
// };

// if (key in keyMap) {
//   return keyMap[key]();
// }
// return '';
// }
